﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FtpWorkerRole.FtpServer;
using System.IO;

namespace FtpWorkerRole.FtpCommand
{
    class ListCommand : CommandBase
    {
        public ListCommand(FtpSocketHandler handler)
            :base(handler)
        {
            commandName = "LIST";
        }

        public override void execute(string value)
        {
            if (!handler.Login)
            {
                Utils.sendMessage(handler.getSocket(), formatMessage(530, "Please Login!"));
                return;
            }
            string path = handler.currentDirectory;
            string[] files;
            string[] dirs;
            value = value.Trim();
            if (value != "")
                path = Path.Combine(path, value);
            Utils.sendMessage(handler.getSocket(), formatMessage(150, "Openning Channel Socket"));

            DataSocketHandler datahandler = new DataSocketHandler(handler);
            if (datahandler.open())
            {
                files = handler.fileSystem.listFiles(path);
                dirs = handler.fileSystem.listDirectories(path);
                var reply = buildList(dirs) + buildList(files);
                if (reply.Length == 0)
                {
                    reply = " ";
                }
                datahandler.sendString(reply);
                datahandler.close();

                Utils.sendMessage(handler.getSocket(), formatMessage(226, "List Complete"));
            }
            else
            {
                Utils.sendMessage(handler.getSocket(), formatMessage(550, "Openning Channel Socket failed."));
            }
        }

        private string buildList(string[] list)
        {
            return buildSimpleList(list);
        }
        private string buildSimpleList(string[] list)
        {
            string fileList = string.Join("\r\n", list);
            fileList += "\r\n";
            return fileList;
        }
    }
}
